<script setup>
import { reactive, onMounted, toRefs, ref, defineProps, inject } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
const props = defineProps({
  test: Object
})
const sw = ref(0)
const sh = ref(0)
const moveX = ref(20)
const moveY = ref(80)
const cartW = ref(0)
const cartH = ref(0)
const store = useStore()
const router = useRouter()
const cartItemNum = inject('cartNum')
console.log('cartItemNum', cartItemNum)
const pageMove = function (e) { }
const touchStart = (e) => {
  console.log('start')
  stopMove()
}
const touchMove = (e) => {
  var touch = e.targetTouches[0]
  var mx = touch.clientX
  var my = touch.clientY
  var tmpx = sw.value - mx - cartW.value / 2
  var tmpy = sh.value - my - cartH.value / 2
  if (tmpx < 0) {
    tmpx = 5
  } else if (tmpx > (sw.value - cartW.value)) {
    tmpx = sw.value - cartW.value - 5
  }
  if (tmpy < 80) {
    tmpy = 80
  } else if (tmpy > (sh.value - cartH.value - 40)) {
    tmpy = sh.value - cartH.value - 40
  }
  moveX.value = tmpx < 0 ? 0 : tmpx
  moveY.value = tmpy
}
const touchEnd = (e) => {
  console.log('end', e)
  Move()
}
// 停止页面滚动
const stopMove = () => {
  document.body.style.overflow = 'hidden'
  document.addEventListener('touchmove', pageMove, { passive: false })
}
// 开启页面滚动
const Move = () => {
  document.body.style.overflow = ''
  document.removeEventListener('touchmove', pageMove, { passive: true })
}
const toOrder = () => {
  router.push({
    path: '/order'
  })
  store.commit('SET_ACTIVE_TABBAR', 1)
}
onMounted(() => {
  var w = document.body.clientWidth
  var h = document.body.clientHeight
  cartW.value = document.getElementById('cart').clientWidth
  cartH.value = document.getElementById('cart').clientHeight
  console.log(w, h, cartW, cartH)
  sw.value = w
  sh.value = h
})
</script>
<template>
  <div class="cart-box" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" id="cart" @click="toOrder()">
    <van-badge :content="cartItemNum">
     <van-icon name="cart" size="35" color="#00A4FF"/>
    </van-badge>
  </div>
</template>

<style>
.cart-box {
  width: 60px;
  height: 60px;
  position: fixed;
  background-color: white;
  border-radius: 50%;
  bottom: v-bind(moveY+ 'px');
  right: v-bind(moveX+ 'px');
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  z-index: 100;
  box-shadow: 2px 2px 1px rgba(0,0,255,.5);
}

</style>
